package com.xinziruo.richclient.support.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.xinziruo.richclient.support.command.Command;
import com.xinziruo.richclient.support.command.CommandConverter;
import com.xinziruo.richclient.support.command.impl.IoBufferCommandConverter;

/**
 * 
 * @author loudyn
 * 
 */
public class CommandProtocolEncoder extends ProtocolEncoderAdapter {

	private CommandConverter<IoBuffer> converter = new IoBufferCommandConverter();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.mina.filter.codec.ProtocolEncoder#encode(org.apache.mina.core.session.IoSession,
	 * java.lang.Object, org.apache.mina.filter.codec.ProtocolEncoderOutput)
	 */
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		if (!isCommandMessage(message)) {
			return;
		}

		Command comm = (Command) message;
		IoBuffer buf = converter.fromCommand(comm);
		out.write(buf.flip());
		out.flush();
	}

	private boolean isCommandMessage(Object message) {
		return Command.class.isAssignableFrom(message.getClass());
	}
}
